# _*_ coding:utf-8 _*_
# @Time  : 2022.06.01
# @Author: zizlee
# 分类指标

from fastapi import APIRouter, Header, Body
from pydantic import BaseModel, conint

from hutool import security, utils as tool_utils
from db import FAConnection, RuizyEDBConnection
from v1_all_api.all_response import AllResponse

classify_index_api = APIRouter()


class IndexCategoryItem(BaseModel):
    dataid: conint(ge=1)
    variety: str


@classify_index_api.post('/')
async def classify_index(ruizy_token: str = Header(...), category: IndexCategoryItem = Body(...)):
    user_obj = security.decrypt_access_token(ruizy_token)
    if not user_obj:
        return AllResponse.no_authorization()
    # 验证数据
    belong_variety = tool_utils.full_width_to_half_width(category.variety).upper().split(',')
    # 过滤不正确的品种
    fa_conn = FAConnection()
    sys_variety = fa_conn.query("SELECT id,variety_en FROM ruizy_variety;")
    sys_variety_list = [v['variety_en'] for v in sys_variety]
    belong_variety = list(filter(lambda x: x in sys_variety_list, belong_variety))
    # 修改分类
    update_sql = "UPDATE all_ruizy_sheet SET variety=%s WHERE id=%s LIMIT 1;"
    edb_conn = RuizyEDBConnection()
    success = edb_conn.execute(update_sql, param=[','.join(belong_variety), category.dataid])
    return AllResponse.operate_successfully() if success else AllResponse.server_error()
